<?php
// 【最终完整版】m-merchant/do_rename.php
session_start();
header('Content-Type: application/json; charset=utf-8');

function verify_token($token) {
    $secret_key = 'kkcc.vip-is-the-best-!@#$%';
    if (!$token) return null; $token_parts = explode('.', $token);
    if (count($token_parts) !== 3) return null; list($h, $p, $s) = $token_parts;
    $sig = base64_decode(str_replace(['-','_'],['+','/'], $s));
    $exp_sig = hash_hmac('sha256', $h.".".$p, $secret_key, true);
    if (!hash_equals($exp_sig, $sig)) return null;
    $payload = json_decode(base64_decode(str_replace(['-','_'],['+','/'], $p)), true);
    if ($payload === null || ($payload['exp']??0) < time()) return null;
    return $payload['data'];
}
function get_authorization_header() {
    if (isset($_SERVER['Authorization'])) return trim($_SERVER["Authorization"]);
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) return trim($_SERVER["HTTP_AUTHORIZATION"]);
    if (function_exists('getallheaders')) {
        $h = getallheaders(); if (isset($h['Authorization'])) return trim($h['Authorization']);
    } return null;
}
function is_valid_id_card($id) {
    $id=strtoupper($id); $regx="/(^\d{17}([0-9]|X)$)/"; if(!preg_match($regx,$id)) return false;
    $id_card_base=substr($id,0,17); if(!check_birth($id_card_base)) return false;
    if(get_verify_code($id_card_base)!=substr($id,17,1)) return false; return true;
}
function get_verify_code($b){if(strlen($b)!=17)return false;$f=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];$v=['1','0','X','9','8','7','6','5','4','3','2'];$s=0;for($i=0;$i<17;$i++){$s+=substr($b,$i,1)*$f[$i];}return $v[$s%11];}
function check_birth($b){$y=substr($b,6,4);$m=substr($b,10,2);$d=substr($b,12,2);if($y<1900||$y>date('Y')||$m>12||$m==0||$d>31||$d==0)return false;return true;}

$user_data = verify_token(str_replace('Bearer ', '', get_authorization_header()));
if ($user_data === null) { http_response_code(401); echo json_encode(['status' => -99, 'msg' => '登录失效']); exit(); }

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$response = ['status' => -1, 'msg' => '无效的请求'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $rename = $_POST['proxy_rename'] ?? ''; $uid = $_POST['proxy_uid'] ?? '';
    $phone = $_POST['proxy_phone'] ?? ''; $submitted_code = $_POST['verification_code'] ?? '';

    if (!preg_match('/^[\x{4e00}-\x{9fa5}]{2,10}$/u', $rename)) { $response['msg'] = '请输入2-10个汉字的真实姓名！'; echo json_encode($response); exit; }
    if (!is_valid_id_card($uid)) { $response['msg'] = '请输入一个合法的18位身份证号码！'; echo json_encode($response); exit; }
    if (!preg_match('/^1[3-9]\d{9}$/', $phone)) { $response['msg'] = '请输入一个有效的手机号码！'; echo json_encode($response); exit; }

    $session_code = $_SESSION['sms_code'] ?? null; $session_phone = $_SESSION['sms_phone'] ?? null;
    if (empty($submitted_code) || $submitted_code != $session_code || $phone != $session_phone) {
        $response['msg'] = '短信验证码错误或已失效！'; echo json_encode($response); exit;
    }
    unset($_SESSION['sms_code']); unset($_SESSION['sms_phone']);

    $proxy_acc_safe = mysqli_real_escape_string($con, $user_data['proxy_acc']);
    $rename_safe = mysqli_real_escape_string($con, $rename); $uid_safe = mysqli_real_escape_string($con, $uid); $phone_safe = mysqli_real_escape_string($con, $phone);
    $sql = "UPDATE proxy SET proxy_rename=?, proxy_uid=?, proxy_phone=?, proxy_rename_sta=1 WHERE proxy_acc=?";
    $stmt = mysqli_prepare($con, $sql);
    mysqli_stmt_bind_param($stmt, "ssss", $rename_safe, $uid_safe, $phone_safe, $proxy_acc_safe);
    if (mysqli_stmt_execute($stmt)) { $response = ['status' => 0, 'msg' => '实名认证成功！']; }
    else { $response['msg'] = '认证失败，数据库更新错误。'; }
    mysqli_stmt_close($stmt);
}
echo json_encode($response);
mysqli_close($con);
?>